import {
  FormEvent,
  FormEventInfo,
  FormActionInfo,
  FormEventBusDefinition
} from '@/components/form-design/event/type';

export const ACTION_MAP: Map<string, FormActionInfo> = new Map<string, FormActionInfo>();

export const EVENT_MAP: Map<string, FormEventInfo> = new Map<string, FormEventInfo>();


const getStartNode = (nodes: any) => {
  let result = null;
  nodes.forEach((node: any) => {
    if (node.type === 'start') {
      result = node;
    }
  });
  return result;
};

const getNextEdge = (edges: any, startNodeId: string) => {
  return edges.filter((edge: any) => edge.source === startNodeId);
};

const getNextNode = (nodes: any, targetNodeId: string) => {
  const targetNodes = nodes.filter((node: any) => node.id === targetNodeId);
  if (targetNodes.length === 1) {
    return targetNodes[0];
  }
  return null;
};

const exeTargetAction = (actionFormId: string, actionEventKey: string, args: any) => {
  const actionInfo = ACTION_MAP.get(actionFormId);
  if (actionInfo && actionInfo.actionList) {
    const actionInfoItem = actionInfo.actionList.find((item: any) => item.key === actionEventKey);
    console.log('actionInfoItem', actionInfoItem);
    // @ts-ignore
    return actionInfoItem.action(args);
  }
  return null;
};


const doExeAction = (event: FormEvent, config: any, startNodeId: string) => {
  const nextEdges = getNextEdge(config.edges, startNodeId);
  console.log(nextEdges);
  if (nextEdges && nextEdges.length > 0) {
    nextEdges.forEach((edge: any) => {
      const targetNode = getNextNode(config.nodes, edge.target);
      if (targetNode && targetNode.type === 'deal') {
        console.log('targetNode', targetNode.data);
        //  TODO 参数转换 ？？
        const result = exeTargetAction(targetNode.data.formId, targetNode.data.eventKey, event.args);
        //  TODO result 合并到CONTEXT 中 ??
        console.log('result', result);
        doExeAction(event, config, targetNode.id);
      }
    });
  }
};

const exeAction = (event: FormEvent, config: any) => {
  if (config.configs && config.configs.nodes) {
    const startNode = getStartNode(config.configs.nodes);
    // @ts-ignore
    if (startNode && startNode.data && event.sourceFormId === startNode.data.formId && event.sourceEventKey === startNode.data.eventKey) {
      // @ts-ignore
      doExeAction(event, config.configs, startNode.id);
    }
  }
};


// TODO 配置设计完成 完善方法  实现图算法？
export const EVENT_BUS: FormEventBusDefinition = {
  eventConfigs: {},
  submitEvent(event: FormEvent) {
    console.log(event);
    console.log(this.eventConfigs.value);
    if (this.eventConfigs.value) {
      this.eventConfigs.value.forEach((config: any) => {
        exeAction(event, config);
      });
    }
  }
};